package com.wanlong.admin.authorizaton;

import com.wanlong.rpc.service.SysMemberManagerService;
import com.wanlong.sys.model.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service("sysUserAuthRealm")
public class SysUserRealm extends AuthorizingRealm {

    @Autowired
    public SysMemberManagerService sysMemberManagerService;

    /**
     * 权限验证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String loginName = (String) principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo simpleAuthorizationInfo = this.getAuthorize(loginName);
        return simpleAuthorizationInfo;
    }

    /**
     * 身份验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        SysUser sysUser = sysMemberManagerService.getSysUserByLoginName(token.getUsername());
        if(sysUser != null){
            //用户名密码验证
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(sysUser.getLoginName(),
                    sysUser.getPassword(),sysUser.getLoginName());
            return simpleAuthenticationInfo;
        }else{
            return null;
        }
    }


    /**
     * 获取用户授权信息
     * @param loginName
     * @return
     */
    private SimpleAuthorizationInfo getAuthorize(String loginName) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        return  simpleAuthorizationInfo;
    }

    /**
     * 设置自定义密码验证
     */
    @PostConstruct
    public void initCredentialsMatcher(){
        setCredentialsMatcher(new CustomCredentialsMatcher());
    }

}
